package com.game.doudizhu.service;

import com.game.doudizhu.model.Player;
import com.game.doudizhu.common.constants.GameConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.cache.annotation.CacheEvict;

@Service
public class StatisticsService {

    @Autowired
    private PlayerService playerService;

    @Autowired
    private CacheService cacheService;

    @Transactional
    @CacheEvict(value = {"rankings", "playerStats"}, allEntries = true)
    public void updateGameStatistics(Long playerId, boolean isWinner, int score, String role) {
        Player player = playerService.getPlayer(playerId);
        if (player != null) {
            // 更新基础统计
            player.setGamesPlayed(player.getGamesPlayed() + 1);
            if (isWinner) {
                player.setGamesWon(player.getGamesWon() + 1);
            }
            player.setScore(player.getScore() + score);

            // 更新角色相关统计
            if (GameConstants.Role.LANDLORD.equals(role)) {
                player.setLandlordGames(player.getLandlordGames() + 1);
                if (isWinner) {
                    player.setLandlordWins(player.getLandlordWins() + 1);
                }
            } else {
                player.setFarmerGames(player.getFarmerGames() + 1);
                if (isWinner) {
                    player.setFarmerWins(player.getFarmerWins() + 1);
                }
            }

            // 保存玩家数据
            playerService.updatePlayer(player);

            // 更新缓存
            cacheService.updatePlayerStats(player);
            
            // 清除排行榜缓存，让它重新计算
            clearRankingCache();
        }
    }

    public double calculateWinRate(Player player) {
        if (player.getGamesPlayed() == 0) {
            return 0.0;
        }
        return (double) player.getGamesWon() / player.getGamesPlayed() * 100;
    }

    public double calculateLandlordWinRate(Player player) {
        if (player.getLandlordGames() == 0) {
            return 0.0;
        }
        return (double) player.getLandlordWins() / player.getLandlordGames() * 100;
    }

    public double calculateFarmerWinRate(Player player) {
        if (player.getFarmerGames() == 0) {
            return 0.0;
        }
        return (double) player.getFarmerWins() / player.getFarmerGames() * 100;
    }

    public double calculateAverageScore(Player player) {
        if (player.getGamesPlayed() == 0) {
            return 0.0;
        }
        return (double) player.getScore() / player.getGamesPlayed();
    }

    @CacheEvict(value = "rankings", allEntries = true)
    public void clearRankingCache() {
        // 方法体可以为空，注解会处理缓存清除
    }
} 